import React, { useState } from 'react';
import { Form, Select, Button, Space, Row, Col, Input, InputNumber, Tooltip } from 'antd';
import { FilterOutlined, ClearOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons';

const { Option } = Select;

interface ApiFilterBarProps {
    onFilterChange: (filters: any) => void;
    loading: boolean;
}

const ApiFilterBar: React.FC<ApiFilterBarProps> = ({ onFilterChange, loading }) => {
    const [form] = Form.useForm();
    const [filters, setFilters] = useState<any>({});
    const [searchKeyword, setSearchKeyword] = useState('');
    const [advancedVisible, setAdvancedVisible] = useState(false);

    // 通用搜索处理
    const handleQuickSearch = (keyword: string) => {
        setSearchKeyword(keyword);
        
        if (!keyword.trim()) {
            const formValues = form.getFieldsValue();
            onFilterChange(formValues);
            return;
        }
        
        // 使用 keyword 字段进行通用搜索
        const searchParams = {
            keyword: keyword.trim(),
            ...form.getFieldsValue()
        };
        
        onFilterChange(searchParams);
    };

    // 处理筛选条件变化
    const handleFilterChange = (changedValues: any, allValues: any) => {
        const newFilters = { ...allValues };
        
        // 如果有搜索关键词，添加到筛选条件中
        if (searchKeyword.trim()) {
            newFilters.keyword = searchKeyword.trim();
        }
        
        // 清理空值
        Object.keys(newFilters).forEach(key => {
            if (newFilters[key] === undefined || newFilters[key] === null || newFilters[key] === '') {
                delete newFilters[key];
            }
        });

        setFilters(newFilters);
        onFilterChange(newFilters);
    };

    // 重置筛选条件
    const handleReset = () => {
        form.resetFields();
        setSearchKeyword('');
        setFilters({});
        onFilterChange({});
    };

    // 快速筛选高频API
    const handleQuickFilterHighFreq = () => {
        const newFilters = { callFrequencyCategory: 'high' };
        form.setFieldsValue(newFilters);
        setFilters(newFilters);
        onFilterChange(newFilters);
    };

    return (
        <div style={{ 
            background: 'linear-gradient(135deg, #52c41a 0%, #73d13d 100%)', 
            padding: '24px', 
            borderRadius: '12px', 
            marginBottom: '24px',
            boxShadow: '0 8px 32px rgba(82, 196, 26, 0.15)'
        }}>
            {/* 主搜索区域 */}
            <div style={{ marginBottom: 20 }}>
                <div style={{ 
                    background: '#fff', 
                    borderRadius: '8px', 
                    padding: '16px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                }}>
                    {/* 搜索框和常用筛选 */}
                    <Form layout="inline" form={form} onValuesChange={handleFilterChange} style={{ width: '100%' }}>
                        <div style={{ display: 'flex', gap: '12px', alignItems: 'flex-end', flexWrap: 'wrap', width: '100%' }}>
                            {/* 通用搜索框 */}
                            <div style={{ flex: 1, minWidth: '300px' }}>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    🔍 通用搜索
                                </label>
                                <Input
                                    size="large"
                                    placeholder="输入关键词搜索包名、类名、方法名或服务名..."
                                    value={searchKeyword}
                                    onChange={(e) => setSearchKeyword(e.target.value)}
                                    onPressEnter={() => handleQuickSearch(searchKeyword)}
                                    prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                                    allowClear
                                    onClear={() => handleQuickSearch('')}
                                    style={{ borderRadius: '6px' }}
                                />
                            </div>

                            {/* 服务类型 */}
                            <div>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    🏷️ 服务类型
                                </label>
                                <Form.Item name="serviceType" style={{ margin: 0 }}>
                                    <Select 
                                        size="large"
                                        style={{ width: 140 }} 
                                        allowClear 
                                        placeholder="选择类型"
                                    >
                                        <Option value="DUBBO">DUBBO</Option>
                                        <Option value="REST">REST</Option>
                                    </Select>
                                </Form.Item>
                            </div>

                            {/* APM记录 */}
                            <div>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    📈 APM记录
                                </label>
                                <Form.Item name="hasApmRecord" style={{ margin: 0 }}>
                                    <Select 
                                        size="large"
                                        style={{ width: 120 }} 
                                        allowClear
                                        placeholder="APM筛选"
                                    >
                                        <Option value="true">有APM记录</Option>
                                        <Option value="false">无APM记录</Option>
                                    </Select>
                                </Form.Item>
                            </div>

                            {/* SA记录 */}
                            <div>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    📊 SA记录
                                </label>
                                <Form.Item name="hasSaRecord" style={{ margin: 0 }}>
                                    <Select 
                                        size="large"
                                        style={{ width: 120 }} 
                                        allowClear
                                        placeholder="SA筛选"
                                    >
                                        <Option value="true">有SA记录</Option>
                                        <Option value="false">无SA记录</Option>
                                    </Select>
                                </Form.Item>
                            </div>

                            {/* 废弃风险 */}
                            <div>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    ⚠️ 废弃风险
                                </label>
                                <Form.Item name="deprecationLevel" style={{ margin: 0 }}>
                                    <Select 
                                        size="large"
                                        style={{ width: 140 }} 
                                        allowClear 
                                        placeholder="选择风险"
                                    >
                                        <Option value="EXTREME_RISK">
                                            <span style={{ color: '#cf1322', fontWeight: 500 }}>● 极高风险</span>
                                        </Option>
                                        <Option value="HIGH_RISK">
                                            <span style={{ color: '#ff4d4f', fontWeight: 500 }}>● 高风险</span>
                                        </Option>
                                        <Option value="MEDIUM_RISK">
                                            <span style={{ color: '#fa8c16', fontWeight: 500 }}>● 中等风险</span>
                                        </Option>
                                        <Option value="LOW_RISK">
                                            <span style={{ color: '#fadb14', fontWeight: 500 }}>● 低风险</span>
                                        </Option>
                                        <Option value="MINIMAL_RISK">
                                            <span style={{ color: '#52c41a', fontWeight: 500 }}>● 极低风险</span>
                                        </Option>
                                    </Select>
                                </Form.Item>
                            </div>

                            {/* 快速排序 */}
                            <div>
                                <label style={{ 
                                    display: 'block', 
                                    marginBottom: '6px', 
                                    fontSize: '14px', 
                                    fontWeight: '500',
                                    color: '#333'
                                }}>
                                    🔄 快速排序
                                </label>
                                <Form.Item name="quickSort" style={{ margin: 0 }}>
                                    <Select 
                                        size="large"
                                        style={{ width: 180 }} 
                                        allowClear 
                                        placeholder="选择排序方式"
                                        onChange={(value) => {
                                            if (value) {
                                                const [orderBy, orderByType] = value.split('_');
                                                form.setFieldsValue({ orderBy, orderByType });
                                            } else {
                                                form.setFieldsValue({ orderBy: undefined, orderByType: undefined });
                                            }
                                        }}
                                    >
                                        <Option value="noCodeChangeDurationDays_desc">📅 修改时间 ↓</Option>
                                        <Option value="noCodeChangeDurationDays_asc">📅 修改时间 ↑</Option>
                                        <Option value="lastInvocationTime_desc">📞 调用时间 ↓</Option>
                                        <Option value="lastInvocationTime_asc">📞 调用时间 ↑</Option>
                                        <Option value="deprecationScore_desc">⚠️ 废弃风险 ↓</Option>
                                        <Option value="deprecationScore_asc">⚠️ 废弃风险 ↑</Option>
                                    </Select>
                                </Form.Item>
                            </div>

                            {/* 搜索按钮 */}
                            <div>
                                <Button 
                                    type="primary" 
                                    size="large"
                                    onClick={() => {
                                        const formValues = form.getFieldsValue();
                                        if (searchKeyword.trim()) {
                                            handleQuickSearch(searchKeyword);
                                        } else {
                                            handleFilterChange({}, formValues);
                                        }
                                    }}
                                    icon={<SearchOutlined />}
                                    style={{ 
                                        background: 'linear-gradient(135deg, #52c41a 0%, #73d13d 100%)',
                                        border: 'none',
                                        borderRadius: '6px',
                                        height: '40px',
                                        paddingLeft: '24px',
                                        paddingRight: '24px'
                                    }}
                                >
                                    搜索
                                </Button>
                            </div>
                        </div>

                        {/* 隐藏的排序字段 */}
                        <Form.Item name="orderBy" style={{ display: 'none' }}>
                            <Input />
                        </Form.Item>
                        <Form.Item name="orderByType" style={{ display: 'none' }}>
                            <Input />
                        </Form.Item>
                    </Form>
                </div>
                
                {/* 操作按钮区 */}
                <div style={{ 
                    marginTop: 12, 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center' 
                }}>
                    <div style={{ display: 'flex', gap: '12px' }}>
                        <Button
                            type="text"
                            size="small"
                            icon={<SettingOutlined />}
                            onClick={() => setAdvancedVisible(!advancedVisible)}
                            style={{ 
                                color: '#fff',
                                fontWeight: '500'
                            }}
                        >
                            {advancedVisible ? '收起高级查询' : '展开高级查询'}
                        </Button>
                    </div>
                    
                    <Button
                        type="text"
                        size="small"
                        icon={<ClearOutlined />}
                        onClick={handleReset}
                        style={{ 
                            color: '#fff',
                            fontWeight: '500'
                        }}
                    >
                        清除所有条件
                    </Button>
                </div>
            </div>

            {/* 高级查询面板 */}
            {advancedVisible && (
                <div style={{ 
                    background: 'rgba(255, 255, 255, 0.95)', 
                    padding: '20px', 
                    borderRadius: '8px',
                    backdropFilter: 'blur(10px)',
                    border: '1px solid rgba(255, 255, 255, 0.2)',
                    boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
                }}>
                    <div style={{
                        fontSize: '16px',
                        fontWeight: '600',
                        color: '#333',
                        marginBottom: '16px',
                        display: 'flex',
                        alignItems: 'center'
                    }}>
                        ⚙️ 高级查询条件
                    </div>
                    
                    <Form 
                        layout="inline" 
                        form={form} 
                        onValuesChange={handleFilterChange}
                        style={{ gap: '12px' }}
                    >
                        {/* 精确字段查询 */}
                        <div style={{ width: '100%', marginBottom: '16px' }}>
                            <div style={{ 
                                fontSize: '14px', 
                                fontWeight: '500', 
                                color: '#666', 
                                marginBottom: '8px' 
                            }}>
                                📍 精确字段查询
                            </div>
                            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                                <Form.Item name="packageName" label="包名">
                                    <Input 
                                        placeholder="精确包名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="className" label="类名">
                                    <Input 
                                        placeholder="精确类名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="methodName" label="方法名">
                                    <Input 
                                        placeholder="精确方法名查询" 
                                        allowClear 
                                        style={{ width: 200 }}
                                    />
                                </Form.Item>
                                
                                <Form.Item name="serviceName" label="服务名">
                                    <Input 
                                        placeholder="服务名查询" 
                                        allowClear 
                                        style={{ width: 220 }}
                                    />
                                </Form.Item>
                            </div>
                        </div>

                        {/* 时间范围查询 */}
                        <div style={{ width: '100%', marginBottom: '16px' }}>
                            <div style={{ 
                                fontSize: '14px', 
                                fontWeight: '500', 
                                color: '#666', 
                                marginBottom: '8px' 
                            }}>
                                ⏱️ 时间范围查询
                            </div>
                            <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
                                <Form.Item name="noSaCallDurationDays" label="累计无调用时长">
                                    <Tooltip title="查找累计无调用时长大于等于指定天数的API">
                                        <InputNumber 
                                            min={0} 
                                            placeholder="天数" 
                                            style={{ width: 120 }}
                                            addonAfter="天"
                                        />
                                    </Tooltip>
                                </Form.Item>
                                
                                <Form.Item name="noCodeChangeDurationDays" label="累计无修改时长">
                                    <Tooltip title="查找累计无修改时长大于等于指定天数的API">
                                        <InputNumber 
                                            min={0} 
                                            placeholder="天数" 
                                            style={{ width: 120 }}
                                            addonAfter="天"
                                        />
                                    </Tooltip>
                                </Form.Item>
                            </div>
                        </div>
                        
                        {/* 操作按钮 */}
                        <div style={{ width: '100%', textAlign: 'center' }}>
                            <Space size="middle">
                                <Button 
                                    type="primary" 
                                    htmlType="submit" 
                                    icon={<SearchOutlined />}
                                    size="large"
                                    style={{
                                        background: 'linear-gradient(135deg, #52c41a 0%, #73d13d 100%)',
                                        border: 'none',
                                        borderRadius: '6px',
                                        paddingLeft: '24px',
                                        paddingRight: '24px'
                                    }}
                                >
                                    执行高级查询
                                </Button>
                                <Button 
                                    htmlType="button" 
                                    onClick={() => form.resetFields()}
                                    icon={<ClearOutlined />}
                                    size="large"
                                    style={{
                                        borderRadius: '6px',
                                        paddingLeft: '20px',
                                        paddingRight: '20px'
                                    }}
                                >
                                    重置条件
                                </Button>
                            </Space>
                        </div>
                    </Form>
                </div>
            )}
        </div>
    );
};

export default ApiFilterBar;